package com.hsogoo.study.concurrency;

import org.junit.Test;

/**
 * MyLock的测试类
 * 启动10个线程对同一变量进行修改
 */
public class MyLockTest {

    private int count;
    private MyLock myLock = new MyLock();

    @Test
    public void testMyLock(){
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(new ModifyThread(i));
            t.start();
        }
    }

    public class ModifyThread implements Runnable {

        private int updateNum;

        public ModifyThread(int updateNum){
            this.updateNum = updateNum;
        }

        @Override
        public void run() {
            try{
                myLock.lock();
                System.out.println("Thread " + updateNum + " get lock");
                int before = count;
                count = updateNum;
                System.out.println("modify count " + before + " to " + count);
            }finally {
                myLock.unlock();
            }
        }
    }
}
